//
//  JCommentController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/13.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JCommentController.h"
#import "JSelImgView.h" // 选择图片按钮
#import <QBImagePickerController/QBImagePickerController.h>

@interface JCommentController () <QBImagePickerControllerDelegate ,UIImagePickerControllerDelegate, UINavigationControllerDelegate>


@property (strong, nonatomic) QBImagePickerController *imagePickerController;

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) NSMutableArray *starBtnArr;
@property (nonatomic, strong) NSMutableArray *selImgBtnArr;
@property (nonatomic, strong) NSMutableArray *selImgArr;
@property (nonatomic, assign) NSInteger selImgNum;
@property (nonatomic, assign) NSInteger selBtnTag;

@property (nonatomic, assign) NSInteger selNumbtn;

@property (nonatomic, strong) UIButton *isName;

@end

@implementation JCommentController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    _selNumbtn = 4;
    
    self.titleLabel.text = @"评论";
    self.leftButton.hidden = NO;
    self.rightButton. hidden = YES;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
 
    [self setConfigComment];
    [self setConfigStarNum];
    [self setConfigSelImgBtn];
    [self setConfigBottomView];
}

- (void)setConfigComment {
    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(15, 15, kWindowW - 30 , kWindowH/2.0 - 64 - 50)];
    textView.backgroundColor = kRGBColor(245, 245, 245);
    textView.font = [UIFont systemFontOfSize:14];
    [self.contentView addSubview:textView];
    _textView = textView;
    
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"请输入您的留言";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = kRGBColor(206, 206, 210);
    [placeHolderLabel sizeToFit];
    [textView addSubview:placeHolderLabel];
    
    // same font
    textView.font = [UIFont systemFontOfSize:14];
    placeHolderLabel.font = [UIFont systemFontOfSize:14];
    
    [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}

- (void)setConfigSelImgBtn
{
    CGFloat width = kWindowW/3.0;
    _selBtnTag = 0;
    
    for (int i = 0; i < 3; i++) {
        JSelImgView *btn = [[JSelImgView alloc]initWithFrame:CGRectMake(i * width, _textView.bottom + 10, width, width) tag:i];
        [self.contentView addSubview:btn];
        btn.tag = i;
        btn.isBigImg = NO;
        [self.selImgBtnArr addObject:btn];
        
        if (i > 0) {
            btn.hidden = YES;
        }
        
        btn.delImgBtnBlock = ^(NSInteger tag) {
            
            JSelImgView *view = self.selImgBtnArr[i];
            if (view.isBigImg == NO) {
                return ;
            }
            
            [self.selImgArr removeObjectAtIndex:tag];
            
            for (int i = 0; i< self.selImgArr.count; i++) {
                JSelImgView *btn = self.selImgBtnArr[i];
                [btn.imgbtn setImage:self.selImgArr[i] forState:UIControlStateNormal];
            }
            
            _selImgNum -= 1;
            
            if (_selImgNum == 2)
            {
                JSelImgView *btn = self.selImgBtnArr[_selImgNum];
                [btn.imgbtn setImage:[UIImage imageNamed:@"gophone_icon"] forState:UIControlStateNormal];
                btn.isBigImg = NO;
            }
            else  {
                JSelImgView *btn = self.selImgBtnArr[_selImgNum+1];
                btn.isBigImg = NO;
                btn.hidden = YES;
                
                JSelImgView *btn2 = self.selImgBtnArr[_selImgNum];
                [btn2.imgbtn setImage:[UIImage imageNamed:@"gophone_icon"] forState:UIControlStateNormal];
                btn2.isBigImg = NO;
            }
        };
        
        btn.addImgBtnBlock = ^(NSInteger tag) {
            JSelImgView *view = self.selImgBtnArr[tag];
            if (view.isBigImg == NO) {
                [self setImagePickerBtn:tag];
            }
            else
            {
                NSLog(@"放大");
            }
            
        };
    }
}

- (void)setImagePickerBtn:(NSInteger)tag
{
    _selBtnTag = tag;
    
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *xiangji = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self xiangjiMethod:tag];
    }];
    
    UIAlertAction *xiangce = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self xiangceMethod:tag];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [sheetController addAction:xiangji];
    [sheetController addAction:xiangce];
    [sheetController addAction:cancel];
    
    [self presentViewController:sheetController animated:YES completion:nil];

}

- (void)setConfigBottomView {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.contentView.frame) - 50, kWindowW, 50)];
    view.opaque = NO;
    view.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:view];
    
    UIButton *delSelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    delSelBtn.frame = CGRectMake(0, 5, kWindowW/3.0, 40);
    delSelBtn.titleLabel.font = kFONT_TITLE(16);
    [delSelBtn setImage:[UIImage imageNamed:@"yuank"] forState:UIControlStateNormal];
    [delSelBtn setImage:[UIImage imageNamed:@"yesred"] forState:UIControlStateSelected];
    [delSelBtn setTitle:@" 匿名评论" forState:UIControlStateNormal];
    [delSelBtn setTitleColor:kRGBColor(100, 100, 100) forState:UIControlStateNormal];
    
    [delSelBtn addTarget:self action:@selector(SetSelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    delSelBtn.tag = 3;
    [view addSubview:delSelBtn];
    delSelBtn.selected = YES;
    _isName = delSelBtn;
    
    UIButton *editSelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    editSelBtn.frame = CGRectMake(kWindowW - kWindowW/3.0, 5, kWindowW/3.0, 40);
    editSelBtn.titleLabel.font = kFONT_TITLE(16);

    [editSelBtn setTitle:@"发表评论" forState:UIControlStateNormal];
    editSelBtn.backgroundColor = [UIColor redColor];
    [editSelBtn addTarget:self action:@selector(SetSelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    editSelBtn.tag = 2;
    
    [view addSubview:editSelBtn];
    
}

- (void)setConfigStarNum
{
    UIView *starView = [[UIView alloc]initWithFrame:CGRectMake(0, _textView.bottom + 10 + kWindowW/3.0 + 10, kWindowW, 40)];
    starView.opaque = NO;
    starView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:starView];
    
    YYLabel *label = [YYLabel new];
    label.text = @"请你评价";
    label.font = kFONT_TITLE(16);
    label.frame = CGRectMake(15, 0, 75, 40);
    [starView addSubview:label];
    
    for (int i = 0; i < 5; i++) {
        UIButton *editSelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        editSelBtn.frame = CGRectMake( (kWindowW - 40 * 5 - 15) + i * 40, 0, 40, 40);
        editSelBtn.titleLabel.font = kFONT_TITLE(16);
        [editSelBtn setImage:[UIImage imageNamed:@"graystar"] forState:UIControlStateNormal];
        [editSelBtn setImage:[UIImage imageNamed:@"yelstar"] forState:UIControlStateSelected];

        [editSelBtn addTarget:self action:@selector(StarBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        editSelBtn.tag = i;
        [starView addSubview:editSelBtn];
        editSelBtn.selected = YES;
        [self.starBtnArr addObject:editSelBtn];
    }
}

- (void)xiangjiMethod:(NSInteger)tag {
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//        self.imagePC = imagePickerController;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;//no
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.showsCameraControls  = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else{
        
//        jHUDNormal(@"您的设备不支持照相功能!")
    }
}

//#pragma mark  imagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //
    CGFloat width = kWindowW/3.0;
    NSData *imgData = [self resetSizeOfImageData:image maxSize:width];
    image = [UIImage imageWithData:imgData];

    JSelImgView *view = self.selImgBtnArr[_selBtnTag];
    [view.imgbtn setImage:image forState:UIControlStateNormal];
    view.isBigImg = YES;
    [self.selImgArr addObject:image];
    
    _selImgNum = view.tag +1;
    
    if (_selBtnTag < 2) {
        JSelImgView *view2 = self.selImgBtnArr[_selBtnTag+1];
        view2.hidden = NO;
    }
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)xiangceMethod:(NSInteger)tag {
    QBImagePickerController *imagePickerController =[QBImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.mediaType = QBImagePickerMediaTypeImage;//图片
    
    imagePickerController.showsNumberOfSelectedAssets = YES;//在界面下方显示已经选择图像的数量
    
    imagePickerController.maximumNumberOfSelection = 3 - _selImgNum;
    imagePickerController.prompt = [NSString stringWithFormat:@"请选择图片，最多%ld张",3 - _selImgNum];
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

//1.获取到图像
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    
    for (int i = 0; i< assets.count; i++) {
        PHAsset * asset = assets[i];
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        // 同步获得图片, 只会返回1张图片
        options.synchronous = YES;
        
        // 是否要原图
        CGSize size = /* DISABLES CODE */ (YES) ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            [self.selImgArr addObject:result];
         
            JSelImgView *view = self.selImgBtnArr[_selBtnTag+i];
            [view.imgbtn setImage:result forState:UIControlStateNormal];
            view.isBigImg = YES;
            view.hidden = NO;
            _selImgNum += 1;
            
            if (_selImgNum < 3) {
                JSelImgView *view = self.selImgBtnArr[_selImgNum];
                view.isBigImg = NO;
                view.hidden = NO;
            }
            
        }];
        

    }
  
    [self dismissViewControllerAnimated:YES completion:nil];
}
//2.取消获取图像
- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    //do something
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)StarBtnClick:(UIButton *)btn
{
    if (_selNumbtn == btn.tag) {
        return;
    }
    _selNumbtn = btn.tag;
    
    for (int i = 0; i < self.starBtnArr.count; i++) {
        if (i <= _selNumbtn) {
            UIButton *btn = self.starBtnArr[i];
            btn.selected = YES;
        }
        else
        {
            UIButton *btn = self.starBtnArr[i];
            btn.selected = NO;
        }
    }
}

- (void)SetSelBtnClick:(UIButton *)btn
{
    if (btn.tag == 3) {
        btn.selected = !btn.selected;
    }
    else
    {
        if (_textView.text.length <= 0) {
            [SVProgressHUD showErrorWithStatus:@"请输入您的留言"];
            return;
        }
        if (self.selImgArr.count == 0) {
            [SVProgressHUD showErrorWithStatus:@"请选择您的图片"];
            return;
        }
        
        [self submitCommentRequest];
        
        
    }
    
}


- (void)submitCommentRequest {
    NSMutableArray *picArr = [NSMutableArray array];
    
    for (UIImage *img in self.selImgArr) {
        NSData *data = UIImageJPEGRepresentation(img, 0.5f);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        
        
        JPicModel *picModel = [JPicModel new];
        picModel.MimeType = @"image/jpeg";
        picModel.TitleAttribute = encodedImageStr;
        picModel.SeoFilename = @"";
        [picArr addObject:picModel.mj_keyValues];
        
    }
    
    JCommentModel *commentModel = [JCommentModel new];
    NSString *url;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (_inputType == 0) { // 单个商品
        
        commentModel.CustomerId = [GLOBALDATA userInfoModel].CustomerId;
        commentModel.OrderItemId = self.payModel.VendorId;
        commentModel.IsAnonymous = _isName ? 1 : 0;
        commentModel.Rating = _selNumbtn + 1;
        commentModel.ReviewText = _textView.text;
        commentModel.Pics = [NSArray arrayWithArray:picArr];
        
        url = @"Products/ProductComment";
        dic = commentModel.mj_keyValues;
    }
    else // 团购商品
    {
        [dic setValue:@(_isName ? 1 : 0) forKey:@"IsAnonymity"];
        [dic setValue:@(self.groupModel.OnlineServerId) forKey:@"OnlineServerId"];
        [dic setValue:self.groupModel.ServerOrderNo forKey:@"ServerOrderNo"];
        [dic setValue:@(1) forKey:@"IsApproved"];
        [dic setValue:@(_selNumbtn + 1) forKey:@"Score"];
        [dic setValue:_textView.text forKey:@"ReviewContent"];
        [dic setValue:picArr forKey:@"PIC"];
        [dic setValue:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"UserId"];
        url = @"BarberSh/AddServerReview";
    }
    
    //  团购
//    "IsAnonymity": ""，     //是否匿名
//    "OnlineServerId": ""，  //团购产品ID
//    ServerOrderNo："",  //订单号（GUID）
//    IsApproved：ture, //固定值
//    Score：1， //分数
//    ReviewContent：""，评论内容
//    "PIC":[{ //图片必填
//    MimeType:"image/jpeg", /固定值
//    SeoFilename:"", //固定值为空
//    TitleAttribute:"" //base64的内容
//    }]


    
    [JNetManager submitProductCommentRequedtUrl:url
                                      parpemDic:dic
                                        success:^(id response) {
                                            if ([response integerValue] == 1) {
                                                [SVProgressHUD showSuccessWithStatus:@"评论成功"];
                                                
                                                [self.navigationController popViewControllerAnimated:YES];
                                                
                                                 [[NSNotificationCenter defaultCenter] postNotificationName:OrderRefresh object:nil userInfo:nil];
                                                
                                            }
                                        } failure:^(NSString *err) {
                                            [SVProgressHUD showErrorWithStatus:err];
                                        }];
    
}

-(QBImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[QBImagePickerController alloc] init];
        _imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsMultipleSelection = YES;
        _imagePickerController.maximumNumberOfSelection = 3;
    }
    
    return _imagePickerController;
}


- (NSMutableArray *)starBtnArr
{
    if (_starBtnArr == nil) {
        _starBtnArr = [NSMutableArray array];
    }
    return _starBtnArr;
}

- (NSMutableArray *)selImgBtnArr
{
    if (_selImgBtnArr == nil) {
        _selImgBtnArr = [NSMutableArray array];
    }
    return _selImgBtnArr;
}

- (NSMutableArray *)selImgArr
{
    if (_selImgArr == nil) {
        _selImgArr = [NSMutableArray array];
    }
    return _selImgArr;
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}


// 压缩图片
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize
{
    //先调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / 1024;
    CGFloat tempWidth = newSize.width / 1024;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData;
    if (UIImagePNGRepresentation(newImage)) {
        imageData = UIImagePNGRepresentation(newImage);
    }else{
        imageData = UIImageJPEGRepresentation(newImage, 0.5);
    }
    
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > maxSize) {
        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50);
        return finallImageData;
    }
    
    return imageData;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
